package com.simoniu.first;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebServlet(name = "helloServlet", urlPatterns = {"/hello","/haha","/hehe"})
public class HelloServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
        //System.out.println("执行了doGet...");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取指定参数
        String username = req.getParameter("username");
        //用来存储一个对象，也可以称之为存储一个域属性
        req.setAttribute("loginName", username);
        //获取名为xx的域属性
        String loginName = (String) req.getAttribute("loginName");
        System.out.println(loginName);
        //获取所有域属性的名称；
        Enumeration attributeNames = req.getAttributeNames();
        //获取请求体的字节数，GET请求没有请求体，没有请求体返回-1；
        long length = req.getContentLength();
        System.out.println("请求体长度："+length);
        /*
           获取请求类型，如果请求是GET，那么这个方法返回null；如果是POST请求，那么默认
           为application/x-www-form-urlencoded，表示请求体内容使用了URL编码；
        */
        String contentType = req.getContentType();
        //返回请求类型
        System.out.println("请求类型:"+contentType);
        //返回请求方法，例如：GET/POST
        String method = req.getMethod();
        System.out.println("请求方法:"+method);
        //返回请求字符集
        String charset =  req.getCharacterEncoding();
        System.out.println("请求编码:"+charset);
        //返回请求参数
        String queryStr = req.getQueryString();
        System.out.println("请求参数:"+queryStr);
        //返回上下文路径
        String contextPath = req.getContextPath();
        System.out.println("上下文:"+contextPath);
        //返回Servlet路径，例如：/ServletDemo1
        String servletPath = req.getServletPath();
        System.out.println("ServletPath:"+servletPath);
        //返回请求URL路径，例如：http://localhost/Demo1/ServletDemo1即返回除了参数
        StringBuffer requestURL = req.getRequestURL();
        System.out.println("请求URL路径:" + requestURL);
        //返回当前客户端的IP地址
        String ipAddr = req.getRemoteAddr();
        System.out.println("客户端的IP地址:" + ipAddr);
        //返回当前客户端的主机名，但这个方法的实现还是获取IP地址
        String hostName = req.getRemoteHost();
        System.out.println("客户端的主机名:" + hostName);
        //返回请求协议，例如：http
        String schema = req.getScheme();
        System.out.println("请求协议：" + schema);
        //返回主机名，例如：localhost
        String serverName = req.getServerName();
        System.out.println("主机名:" + serverName);
        //返回服务器端口号，例如：8080
        int port = req.getServerPort();
        System.out.println("服务器端口号:" + port);
    }

    public void destroy() {
    }
}